package com.colin.database;

import com.colin.ColinConstant;
import com.colin.util.NotificationUtil;
import com.colin.util.PropertiesManager;
import com.github.weisj.jsvg.T;
import org.apache.commons.lang3.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

public class MysqlDataSource {
    public static <T> List<T> executeSQL(String sql, Class<T> t, Function<ResultSet, T> function) {
        String host = PropertiesManager.getString(ColinConstant.MYSQL_HOST);
        String port = PropertiesManager.getString(ColinConstant.MYSQL_PORT);
        String mysqlDatabase = PropertiesManager.getString(ColinConstant.MYSQL_DATABASE);
        String username = PropertiesManager.getString(ColinConstant.MYSQL_USER_NAME);
        String password = PropertiesManager.getString(ColinConstant.MYSQL_PASS_WORD);
        String url;
//        if (StringUtils.isBlank(host)) {
            url = Config.JDBC_URL_MAN;
//        } else {
//            // 构建数据库连接 URL
//            url = "jdbc:mysql://" + host + ":" + port + "/"
//                    + mysqlDatabase
//                    + "?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&nullCatalogMeansCurrent=true&rewriteBatchedStatements=true";
//        }

        try {
            // 加载 JDBC 驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            try (Connection conn = DriverManager.getConnection(url, Optional.ofNullable(username).orElse(Config.JDBC_UserName), Optional.ofNullable(password).orElse(Config.JDBC_Password))) {
                // 创建 Statement 对象
                try (Statement stmt = conn.createStatement()) {
                    // 执行 SQL 查询
                    try (ResultSet rs = stmt.executeQuery(sql)) {
                        List<T> list = new ArrayList<>();
                        // 处理查询结果
                        while (rs.next()) {
                            // 从结果集中提取数据
                            list.add(function.apply(rs));
                        }
                        return list;
                    }
                } catch (SQLException e) {
                    NotificationUtil.error("SQL 执行失败, e = " + e.getMessage());
                    return Collections.emptyList();
                }
            }
        } catch (ClassNotFoundException | SQLException e) {
            NotificationUtil.error("SQL 执行失败, e = " + e.getMessage());
            return Collections.emptyList();
        }
    }
}
